package com.wh.order.controller;

import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.date.DateUtil;
import com.wh.basic.vo.AjaxResult;
import com.wh.order.dto.*;
import com.wh.order.pojo.OrderReviewer;
import com.wh.order.service.IOrderListService;
import com.wh.order.pojo.OrderList;

import com.wh.order.util.OrderExport;
import com.wh.order.vo.OrderExportVo;
import com.wh.order.vo.OrderProductVo;
import org.apache.commons.codec.Charsets;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 后端接口类；
 */
@Controller
@RequestMapping("/orderList")
@CrossOrigin

public class OrderListController {

    @Autowired
    public IOrderListService orderListService;


//    /**
//     * 选中字段导出
//     */
//    @PostMapping(value = "/export")
//    public void export(HttpServletResponse response, @RequestBody OrderExportPoiDto poiDto) {
//        List<OrderExportDto> exportDtos = poiDto.getExportDto();
//        String orderSn = poiDto.getOrderSn();
//        String[] orderSnArr = null;
//        if(StringUtils.hasLength(orderSn)){
//            orderSnArr = orderSn.split(",");
//        }
//        OrderExport orderExport = orderListService.export(exportDtos,orderSnArr);
//        if (orderExport == null) {
//            return;
//        }
//        String[] labels = orderExport.getLabels();
//        String[] props = orderExport.getProps();
//        List<OrderExportVo> exportVos = orderExport.getExportVos();
//        Workbook workbook = null;
//        // 创建一个新的Workbook
//        try {
//            workbook = new XSSFWorkbook();
//
//            Font headerFont = workbook.createFont();
//            headerFont.setBold(true);
//            // 创建一个Sheet，代表一个工作表
//            Sheet sheet = workbook.createSheet("sheet1");
//            CellStyle headerStyle = workbook.createCellStyle();
//            headerStyle.setFont(headerFont);
//            headerStyle.setAlignment (HorizontalAlignment.CENTER);
//
//            // 创建表头（字段）
//            // 在第一行写入表头
//            Row headerRow = sheet.createRow(0);
//            for (int i = 0; i < labels.length; i++) {
//                if (StringUtils.hasLength(labels[i])) {
//                    Cell cell = headerRow.createCell(i);
//                    cell.setCellValue(labels[i]);
//                    cell.setCellStyle(headerStyle);
//                }
//            }
//
//            for (int i = 1; i < exportVos.size(); i++) {
//                Row row = sheet.createRow(i);
//                for (int j = 0; j < props.length; j++) {
//                    if (StringUtils.hasLength(props[j])) {
//                        Cell cell = row.createCell(j);
//                        if ("amount".equals(props[j])) {
//                            cell.setCellValue((Double) invokeGetMethod(OrderExportVo.class, props[j], exportVos.get(i)));
//                        } else if ("createTime".equals(props[j]) || "lastOperationTime".equals(props[j])) {
//                            String date = DateUtil.format((Date) invokeGetMethod(OrderExportVo.class, props[j], exportVos.get(i)), "yyyy-MM-dd HH:mm:ss");
//                            cell.setCellValue(date);
//                        } else {
//                            cell.setCellValue((String) invokeGetMethod(OrderExportVo.class, props[j], exportVos.get(i)));
//                        }
//                    }
//                }
//            }
//            String fileName = "orderInfo.xlsx";
//            //把生成的excel文件下载到客户端
//            response.setContentType("application/vnd.openxmlformats-officeedocument.sheet;charset=utf-8");
//            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
//            response.setHeader("Access-Control-Allow-Origin", "*");
//            ServletOutputStream os = response.getOutputStream();
//            workbook.write(os);
//            os.flush();
//            os.close();
//            workbook.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//        }
//    }
    /**
     * 订单导出
     * @param response
     *全部导出
     * @throws Exception
     */
    @PostMapping("/export")
    public void exportOrders(HttpServletResponse response, @RequestBody exportOrderDto exportOrderDto)  {
        List<String> orderSn = exportOrderDto.getOrderSn();
        orderListService.exportOrdersAsync(response, orderSn);
    }
    /**
     * 拼接属性，调用目标Class的get方法
     *
     * @param c         属性所属实体类
     * @param fieldName 需要调用的属性名
     * @param obj       实体类实例
     * @return 返回get方法结果
     */
    public static Object invokeGetMethod(Class<?> c, String fieldName, Object obj) {
        try {
            // 确保字段名不是空的
            if (fieldName == null || fieldName.isEmpty()) {
                throw new IllegalArgumentException("Field name cannot be null or empty");
            }

            // 创建 getter 方法名
            String methodName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);

            // 查找方法，指定参数类型为空（对于 getter 方法）
            Method method = c.getMethod(methodName, new Class<?>[]{});

            // 确保 obj 是 c 的一个实例
            if (!c.isInstance(obj)) {
                throw new IllegalArgumentException("Object is not an instance of the specified class");
            }

            // 调用方法并返回结果
            return method.invoke(obj);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            // 处理或重新抛出异常（这里只是简单地将其包装为 RuntimeException）
            throw new RuntimeException(e);
        }
    }


    /**
     * 接口：添加或修改
     *
     * @param orderList 传递的实体
     * @return AjaxResult 响应给前端
     * 订单目前不创建
     */
    @PutMapping
    @ResponseBody
    public AjaxResult addOrUpdate(@RequestBody OrderList orderList) {
        if (orderList.getOrderSn() != null) {
            orderListService.updateById(orderList);
        } else {
            orderListService.saveOrder(orderList);
        }
        return new AjaxResult();

    }

    @GetMapping("/Time")
    @ResponseBody
    public Map<String, Long> getTime() {
        Map<String, Long> listTime = orderListService.getTime();
        return listTime;
    }

    /**
     * 我的订单页面查询数据
     *
     * @param pageDto
     * @return
     */
    @PostMapping("/MyOrder")
    @ResponseBody
    public IPage<OrderList> findByPageMyOrder(@RequestBody PageDto pageDto) {
        return orderListService.findByPageMyOrder(pageDto);
    }

    /**
     * 获取热门产品销售数量（只统计订单为交易成功的）
     *
     * @return
     */
    @PostMapping("getHotProductCount")
    @ResponseBody
    public AjaxResult getHotProductCount(String type) {
        List<OrderProductVo> orderProductVos = orderListService.getHotProductCount(type);
        return AjaxResult.me().setSuccess(true).setResultObj(orderProductVos);
    }

    /**
     * 获取订单总金额（只统计订单交易成功）
     * type 汇总类型  year month week
     *
     * @return
     */
    @PostMapping("getTotalAmount")
    @ResponseBody
    public AjaxResult getTotalAmount(String type) {
        Map<String, Object> datas = orderListService.getTotalAmount(type);
        return AjaxResult.me().setSuccess(true).setResultObj(datas);
    }

    @RequestMapping("/getOrderDataCount")
    @ResponseBody
    public AjaxResult getOrderDataCount(String type) {
        Map<String, Object> datas = orderListService.getOrderDataCount(type);
        return AjaxResult.me().setSuccess(true).setResultObj(datas);
    }

    /**
     * 保存订单
     *
     * @param orderList
     * @return
     */
    @PutMapping("/saveOrder")
    @ResponseBody
    public AjaxResult saveOrder(@RequestBody OrderList orderList) {
        orderListService.saveOrder(orderList);
        return new AjaxResult();
    }

    /**
     * 订单编辑
     *
     * @param orderList
     * @return
     */
    @PutMapping("/editOrder")
    @ResponseBody
    public AjaxResult editOrder(@RequestBody OrderList orderList) {
        orderListService.editOrder(orderList);
        return new AjaxResult();

    }

    /**
     * 查询自己账号的审核订单
     */
    @PostMapping("/auditOrders")
    @ResponseBody
    public IPage<OrderList> getAuditOrders(@RequestBody AuditOrdersDto auditOrdersDto) {
        IPage<OrderList> auditOrders = orderListService.getAuditOrders(auditOrdersDto);
        return auditOrders;
    }

    /**
     * 通过客户id获取客户订单
     *
     * @return
     */
    @PostMapping("/getCustomerOrder")
    @ResponseBody
    public IPage<OrderList> getCustomerOrder(@RequestBody CustomerOrderDto customerOrderDto) {
        IPage<OrderList> customerOrderList = orderListService.getCustomerOrders(customerOrderDto);
        return customerOrderList;
    }

    /**
     * 订单审核
     *
     * @param OrderReviewer
     * @return
     */
    @PutMapping("/Examine")
    @ResponseBody
    public AjaxResult Examine(@RequestBody OrderReviewer OrderReviewer) {
        orderListService.Examine(OrderReviewer);
        return new AjaxResult();
    }


    @GetMapping("/num")
    @ResponseBody
    public Integer all() {
        return orderListService.allNum();
    }

    @PutMapping("/sendoutgoods")
    @ResponseBody
    public AjaxResult sendoutgoods(@RequestBody OrderList orderList) {
        orderListService.sendoutgoods(orderList);

        return new AjaxResult();
    }

    //取消订单
    @PutMapping("/cancel")
    @ResponseBody
    public AjaxResult cancel(@RequestBody OrderList orderList) {
        orderListService.cancel(orderList);

        return new AjaxResult();
    }

    /**
     * 接口：删除
     *
     * @param id
     * @return AjaxResult 响应给前端
     */
    @DeleteMapping(value = "/{orderSn}")
    @ResponseBody
    public AjaxResult del(@PathVariable("orderSn") Long id) {
        orderListService.removeById(id);
        return new AjaxResult();
    }

    /**
     * 接口：批量删除
     *
     * @param ids
     * @return AjaxResult 响应给前端
     */
    @PatchMapping
    @ResponseBody
    public AjaxResult patchDel(@RequestBody List<Long> ids) {
//        orderListService.removeByIds(ids);
        return new AjaxResult();
    }

    /**
     * 接口：查询单个对象
     *
     * @param orderSn
     */
    @GetMapping("/{orderSn}")
    @ResponseBody
    public OrderList findOne(@PathVariable("orderSn") String orderSn) {
        return orderListService.findOne(orderSn);
    }

    /**
     * 接口：分页查询或高级查询
     *
     * @return IPage<OrderList> 分页对象
     */
    @PostMapping
    @ResponseBody
    public IPage<OrderList> findByPage(@RequestBody PageDto pageDto) {
        return orderListService.findByPage(pageDto);
    }


    @PostMapping("/importOrder")
    @ResponseBody
    public AjaxResult importOrder(@RequestPart("file") MultipartFile file ){
        return orderListService.importOrder(file);
    }

    /**
     * 接口：分页查询或高级查询
     * 查询客服下单列表数据，，要求，检索为快递的
     * @return IPage<OrderList> 分页对象
     */
    @PostMapping("/CustomerService")
    @ResponseBody
    public IPage<OrderList> CustomerServiceFindByPage(@RequestBody PageDto pageDto) {
        return orderListService.customerServiceFindByPage(pageDto);
    }

    /**
     * 订单收货
     * @param orderSn
     * @return
     */
    @PutMapping("/takeDelivery/{orderSn}")
    @ResponseBody
    public AjaxResult takeDelivery(@PathVariable("orderSn") String orderSn){
        orderListService.takeDelivery(orderSn);
        return  new AjaxResult();

    }
}
